<?php

namespace App\Transformers;

use App\Models\PhoneSetting;
use App\Models\Role;
use App\Models\User;
use League\Fractal\TransformerAbstract;

class UserTransformer extends TransformerAbstract
{
    protected  $role;
    protected  $setting_id;
    protected  $phone_setting;
    protected  $nameAndPass;

    protected $availableIncludes = ['phones','roles'];

    public function __construct($arr='',$setting_id = '',$nameAndPass='')
    {
        $role = new Role();
        $this->role = $role->getIdAndNameToArray();
        $phoneSetting = new PhoneSetting();
        $this->phone_setting = $phoneSetting->where('status',true)->first();
        $this->setting_id = $setting_id;
        $this->nameAndPass = $nameAndPass;
    }

    public function transform(User $user)
    {
        return [
            'id' => $user->id,
            'name' => $user->name,
            'section' => empty($user->section_id)?'':isset($this->role[$user->section_id])?$this->role[$user->section_id]:'',
            'branch' => empty($user->branch_id)?'':isset($this->role[$user->branch_id])?$this->role[$user->branch_id]:'',
            'role' => empty($user->role_id)?'':isset($this->role[$user->role_id])?$this->role[$user->role_id]:'',
            'section_id' => $user->section_id,
            'branch_id' => $user->branch_id,
            'role_id' => $user->role_id,
            'ip' => $user->login_ip,
            'status' => $user->status,
            'phone_site'=> empty($this->phone_setting)?'':$this->phone_setting->site,
            'phone_setting_id' => empty($this->phone_setting)?'':$this->phone_setting->id,
            'phone_type' => empty($this->phone_setting)?'':$this->phone_setting->type,
            'username' => empty($this->nameAndPass)?'':$this->nameAndPass->username,
            'password' =>  empty($this->nameAndPass)?'':$this->nameAndPass->password,
            'created_at' => empty($user->created_at)?'':$user->created_at->toDateTimeString(),
            'updated_at' => empty($user->updated_at)?'':$user->updated_at->toDateTimeString(),
        ];
    }

    public function includePhones(User $user)
    {
        return $this->collection($user->phones->where('phone_setting_id',$this->setting_id), new PhoneTransformer());
    }

    public function includeRoles(User $user)
    {
        return $this->collection($user->roles->where('is_role',true),new RoleTransformer());
    }
}